package com.testmock;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;

public class VelocityHelper {
    /**
     *
     * @param vmFile  vm源文件名
     * @param ctx  源文件映射字符关系
     * @return 模模板化生成的文本
     * @throws Exception
     */
    public static String generateXML(String vmFile,
                                     VelocityContext ctx) throws Exception {
        try {
            VelocityEngine engine = new VelocityEngine();
            engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
            engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
            engine.init();

            StringWriter writer = new StringWriter();
            Template template = engine.getTemplate(vmFile, "UTF-8");
            template.merge(ctx,writer);
            System.out.println("writer:" + writer.toString());
            return writer.toString();
        } catch (Exception ex) {
            throw ex;
        }
    }
}
